package com.junxi.microservices.bookstore.product.controller;

import com.junxi.microservices.bookstore.product.client.InventoryFeignClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
public class ProductController {

    public static final Logger logger = LoggerFactory.getLogger(ProductController.class);

    private final InventoryFeignClient inventoryFeignClient;

    public ProductController(InventoryFeignClient inventoryFeignClient) {
        this.inventoryFeignClient = inventoryFeignClient;
    }

    // 公开接口，无需认证
    @GetMapping("/public/info")
    public String publicInfo() {
        return "This is public information from Product Service";
    }

    // 需要product.read权限的接口
    @GetMapping("/products")
    public List<String> getProducts(Authentication authentication) {
        return Arrays.asList("Product 1", "Product 2", "Product 3");
    }

    // 需要product.read权限的接口
    @GetMapping("/products/{productId}")
    public ProductResponse getProductsDetail(@PathVariable("productId") String productId, Authentication authentication) {
        logger.info("enter getProductsDetail, id is {}", productId);
    // 调用库存服务获取库存信息
        InventoryFeignClient.InventoryResponse inventory = inventoryFeignClient.checkInventory(Long.parseLong(productId));
        return new ProductResponse(Long.parseLong(productId), "demo-product", 999, inventory.quantity());
    }

    // 需要product.write权限的接口
    @PostMapping("/products")
    public String addProduct(@RequestBody String productName, Authentication authentication) {
        return "Product '" + productName + "' added successfully";
    }

    // 添加产品（需要检查库存）
//    @PostMapping("/products/checkInventory")
//    public Map<String, Object> addProduct(@RequestBody String productName) {
//        // 通过Feign调用inventory-service检查库存
//        Map<String, Object> inventoryInfo = inventoryFeignClient.checkInventory(productName);
//
//        Map<String, Object> response = new HashMap<>();
//        response.put("product", productName);
//        response.put("status", "created");
//        response.put("inventory", inventoryInfo);
//
//        return response;
//    }
    // 需要ADMIN角色的接口
    @DeleteMapping("/admin/products/{id}")
    public String deleteProduct(@PathVariable Long id, Authentication authentication) {
        return "Product " + id + " deleted successfully by " + authentication.getName();
    }

    // 获取当前用户信息
    @GetMapping("/user/info")
    public Authentication getUserInfo(Authentication authentication) {
        return authentication;
    }

    public record ProductResponse(Long id, String name, double price, Integer stockQuantity) {}
}
